package com.linkage.educloud.ah.view.activity.classspace;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.linkage.educloud.ah.R;
import com.linkage.educloud.ah.view.BasicTitleActivity;
import com.linkage.educloud.ah.widget.CommonDialog;
import com.zzhou.common.library.util.LogUtils;
import com.zzhou.common.library.util.ToastShow;

import java.io.IOException;

import butterknife.BindView;

/**
 * Created by Mr'Tang on 2018/10/25.
 */

public class DynamicWriterVoiceActivity extends BasicTitleActivity {

    @BindView(R.id.ac_write_voice_img)
    ImageView ac_write_voice_img;
    @BindView(R.id.ac_write_voice_btn)
    ImageButton ac_write_voice_btn;
    @BindView(R.id.ac_write_voice_text)
    TextView ac_write_voice_text;
    @BindView(R.id.ac_write_voice_teacher)
    LinearLayout ac_write_voice_teacher;
    @BindView(R.id.ac_write_voice_box)
    CheckBox ac_write_voice_box;

    long start_time;//按下时的系统时间
    long end_time;//手指抬起时系统时间


    //语音文件保存路径
    private String FileName = null;

    //语音操作对象
    private MediaPlayer mPlayer = null;
    private MediaRecorder mRecorder = null;

    //存储很多张话筒图片的数组
    private Drawable[] micImages;
    private int BASE = 600;
    private int SPACE = 200;// 间隔取样时间

    private final Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            int what = msg.what;
            //根据mHandler发送what的大小决定话筒的图片是哪一张
            if (what > 13) {
                what = 13;
            }
            ac_write_voice_img.setImageDrawable(micImages[what]);
        }
    };

    private Runnable mUpdateMicStatusTimer = new Runnable() {
        public void run() {
            updateMicStatus();
        }
    };

    private void updateMicStatus() {
        if (mRecorder != null) {
            int ratio = mRecorder.getMaxAmplitude() / BASE;
            int db = 0;// 分贝
            if (ratio > 1)
                db = (int) (20 * Math.log10(ratio));
            System.out.println("分贝值：" + db + "     " + Math.log10(ratio));
            //我对着手机说话声音最大的时候，db达到了35左右，
            mHandler.postDelayed(mUpdateMicStatusTimer, SPACE);
            //所以除了2，为的就是对应14张图片
            mHandler.sendEmptyMessage(db / 4);
        }
    }

    public static void launch(Context context) {
        Intent intent = new Intent(context, DynamicWriterVoiceActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_dynamic_write_voice;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("发声音");

        //给录音按钮设置滑动监听
        ac_write_voice_btn.setOnTouchListener(new MyListener());

        //设置sdcard的路径
        FileName = Environment.getExternalStorageDirectory().getAbsolutePath();
        FileName += "/hejiaoyudynamicvoice.3gp";

        micImages = new Drawable[]{
                getResources().getDrawable(R.mipmap.voice_image_fly0),
                getResources().getDrawable(R.mipmap.voice_image_fly1),
                getResources().getDrawable(R.mipmap.voice_image_fly2),
                getResources().getDrawable(R.mipmap.voice_image_fly3),
                getResources().getDrawable(R.mipmap.voice_image_fly4),
                getResources().getDrawable(R.mipmap.voice_image_fly5),
                getResources().getDrawable(R.mipmap.voice_image_fly6)};
    }


    //按住录音  按住说话，松开发送   松开手指，取消发送 red
    private class MyListener implements View.OnTouchListener {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    start_time = System.currentTimeMillis();
                    ac_write_voice_btn.setBackgroundResource(R.mipmap.voice_image_btn_pressed);
                    ac_write_voice_text.setText("按住说话，松开发送");
                    ac_write_voice_text.setTextColor(Color.WHITE);

                    //开始录音
                    startRecordListener();
                    //开始监听分贝大小
                    updateMicStatus();

                    break;

                case MotionEvent.ACTION_MOVE:
                    if (!isTouchPointInView(ac_write_voice_btn, (int) event.getRawX(), (int) event.getRawY())) {
                        ac_write_voice_img.setImageResource(R.mipmap.voice_image_unsend);
                        ac_write_voice_text.setText("松开手指，取消发送");
                        ac_write_voice_text.setTextColor(Color.RED);
                    } else {
                        ac_write_voice_img.setImageResource(R.mipmap.voice_image_fly0);
                        ac_write_voice_text.setText("按住说话，松开发送");
                        ac_write_voice_text.setTextColor(Color.WHITE);
                    }
                    break;

                case MotionEvent.ACTION_UP:
                    ac_write_voice_img.setImageResource(R.mipmap.voice_image_fly0);
                    ac_write_voice_btn.setBackgroundResource(R.mipmap.voice_image_btn);
                    ac_write_voice_text.setText("按住录音");
                    ac_write_voice_text.setTextColor(Color.WHITE);

                    //结束录音
                    stopRecordListener();

                    if (isTouchPointInView(ac_write_voice_btn, (int) event.getRawX(), (int) event.getRawY())) {
                        end_time = System.currentTimeMillis();

                        //录音时间不能少于一秒
                        if (end_time - start_time < 1000) {
                            ToastShow.show(DynamicWriterVoiceActivity.this, "时间太短,录音失败!");
                        } else {
                            ToastShow.show(DynamicWriterVoiceActivity.this, "录音完成!");
                            playSuccess();
                        }
                    }
                    break;
            }
            return false;
        }
    }

    void playSuccess() {
        CommonDialog dialog = new CommonDialog(DynamicWriterVoiceActivity.this, "选择操作", "", "发送", "播放");
        dialog.setCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastShow.show(DynamicWriterVoiceActivity.this, "发送待添加");
            }
        });
        dialog.setOkListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startPlayListener();
            }
        });
        dialog.show();

        if (!dialog.isShowing())
            stopRecordListener();
    }


    //判断当前触碰点是否还在view内
    private boolean isTouchPointInView(View targetView, int xAxis, int yAxis) {
        if (targetView == null) {
            return false;
        }
        int[] location = new int[2];
        targetView.getLocationOnScreen(location);
        int left = location[0];
        int top = location[1];
        int right = left + targetView.getMeasuredWidth();
        int bottom = top + targetView.getMeasuredHeight();
        if (yAxis >= top && yAxis <= bottom && xAxis >= left
                && xAxis <= right) {
            return true;
        }
        return false;
    }

    //开始录音
    void startRecordListener() {
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(FileName);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        try {
            mRecorder.prepare();
        } catch (IOException e) {
            LogUtils.e(TAG, "prepare failed");
        }
        mRecorder.start();
    }

    //停止录音
    void stopRecordListener() {
        //这里简单粗暴的直接抛出异常 解决拍摄时间过短，还没初始化完就stop而引起的stop.failed的bug
        try {
            mRecorder.stop();
        } catch (RuntimeException stopException) {
        }
        mRecorder.release();
        mRecorder = null;
    }

    //播放录音
    void startPlayListener() {
        mPlayer = new MediaPlayer();
        try {
            mPlayer.setDataSource(FileName);
            mPlayer.prepare();
            mPlayer.start();
        } catch (IOException e) {
            LogUtils.e(TAG, "播放失败");
        }
    }
}
